#include <thread.h>
#include <socket.h>

#include <iostream>
using std::cout;
using std::endl;

//An example of multithreaded Tcp Server
class ThreadAccept : public Thread, public Socket{
public:
	ThreadAccept(Socket &s) : Socket(s)
	{
		locals = &s;
	}
	~ThreadAccept()
	{
		delete locals;
	}
	virtual void accept_thread();

	void run(void *y)
	{
		ThreadAccept *t = (ThreadAccept *)y;
		accept_thread();
		this->~ThreadAccept();
	}
protected:
	Socket *locals;
};

//This is a callback function that is launched after an Socket::accept
void ThreadAccept::accept_thread()
{
	cout << "new connection accepted"<<endl;
	send("hello\ngood bye!\n");
}


class TcpThread : public TcpSocket, public Thread {
public:
	void run(void *y)
	{
		ThreadAccept *a;
		Socket *tmp;
		while(1){
			tmp = accept();
			cout << "accepting a new connection" << endl;
			a = new ThreadAccept(*tmp);
			a->start();
		}
	}
};

int main(int argc, char *argv[])
{
	Net n;
	TcpThread t;
	
	//Make the server listen on port
	if(	t.listen(8090) == false){
		cout << "cannot listen/bind on port 8090" << endl;
		exit(0);
	}
	//Start server(another thread)
	t.start();
	
	cout << "tcp server started and running in another thread"<<endl;
	
	//Wait server to finish(never unless we interrupt it)
	t.wait();
	return 0;
}
